/**
 * ______________________________________________________________________________
 *
 * File: SessionCreation.java
 *______________________________________________________________________________
 *
 * CreatedBy: Verinon
 * CreationDate: Sep 13, 2012   3:00:31 PM   2012
 * Description: Write your class description here like from where it is calling and
 * what functions are doing
 *______________________________________________________________________________
 *
 * Copyright: (c) Vietinbank, all rights reserved 
 *______________________________________________________________________________
 *
 */
package com.vb.ecm.migration.icdoc;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.ResourceBundle;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;

import org.apache.log4j.Logger;

import com.documentum.com.DfClientX;
import com.documentum.com.IDfClientX;
import com.documentum.fc.client.DfClient;
import com.documentum.fc.client.IDfCollection;
import com.documentum.fc.client.IDfFolder;
import com.documentum.fc.client.IDfQuery;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSessionManager;
import com.documentum.fc.client.IDfSysObject;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.DfId;
import com.documentum.fc.common.DfTime;
import com.documentum.fc.common.IDfId;
import com.documentum.fc.common.IDfLoginInfo;
import com.documentum.operations.IDfCheckoutNode;
import com.documentum.operations.IDfCheckoutOperation;
import com.documentum.operations.outbound.DfCheckoutOperation;
import com.vb.ecm.migration.icdoc.StartMigration.SimulatedActivity;

/**
 * @Last Midify Author Verinon
 * @Last Midification Date Sep 13, 2012
 * @Last Midification Time 3:00:31 PM
 * @Last Midification Year 2012
 * @What to do next TODO
 */
public class ExportToDocumentum {

	private static ResourceBundle RSB = ResourceBundle.getBundle("com.vb.ecm.migration.icdoc.migrationtool");
	AccessDatabase accessDatabase2 = new AccessDatabase();
	private static final Logger LOGGER = Logger.getLogger(ExportToDocumentum.class);
	DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");

	/**
	 * Used to create Session Manager, Session and releases Session.
	 */
	private static IDfSession session = null;
	private static IDfSessionManager sMgr = null;

	private static String ICDOCDOCTYPE = RSB.getString("ICDOC_DOC_TYPE");
	private static String CODE = RSB.getString("CODE");
	private static String DOC_SUBJECT = RSB.getString("DOC_SUBJECT");
	private static String NUMBER_SIGN = RSB.getString("NUMBER_SIGN");
	private static String CREATOR_NAME = RSB.getString("CREATOR_NAME");
	private static String ICDOC_PARENT_FOLDER_TYPE = RSB.getString("ICDOC_PARENT_FOLDER_TYPE");
	private static String ICDOC_FOLDER_TYPE = RSB.getString("ICDOC_FOLDER_TYPE");
	private static String IC_DOC_FOLDER_NAME = RSB.getString("IC_DOC_FOLDER_NAME");
	private static String docCodeA = RSB.getString("DOC_CODE");
	private static String ICDOCBRANCHCODE = RSB.getString("ICDOCBRANCHCODE");
	private String branch_number = null;
	private String object_name = null;
	private String page_count = null;
	private String sharing = null;
	private String is_deleted = null;
	private String status_name = null;
	private String cust_cif_number = null;
	private String cust_name = null;
	private String original = null;
	private String creator_code = null;
	private String dep_code = null;
	private String dep_name = null;
	private String sharing_name = null;
	private String cust_id_number = null;
	private String doc_name = null;
	private String creator_name = null;
	private String date_upload = null;
	private String doc_abbreviate_code = null;
	private String doc_abbreviate_group_code = null;
	private String doc_abbreviate_group_name = null;
	private String doc_abbreviate_name = null;
	private String doc_code = null;
	private String doc_subject = null;
	private String doc_upload_status = null;
	private String level_security = null;
	private String level_security_code = null;
	private String number_sign = null;
	private String type_doc_code = null;
	private String type_doc_name = null;
	private String file_type = null;

	private String branch_numberV = null;
	private String object_nameV = null;
	private String doc_nameV = null;
	private String number_signV = null;
	private String doc_codeV = null;
	private String doc_subjectV = null;
	private String page_countV = null;
	private String doc_abbreviate_group_nameV = null;
	private String doc_abbreviate_nameV = null;
	private String type_doc_nameV = null;
	private String level_securityV = null;
	private String date_uploadV = null;
	private String creator_nameV = null;
	private String type_doc_codeV = null;
	private String level_security_codeV = null;
	private String doc_abbreviate_group_codeV = null;
	private String doc_abbreviate_codeV = null;
	private String sharingV = null;
	private String is_deletedV = null;
	private String file_typeV = null;
	private String status_nameV = null;
	private String cust_cif_numberV = null;
	private String cust_id_numberV = null;
	private String cust_nameV = null;
	private String originalV = null;
	private String creator_codeV = null;
	private String dep_codeV = null;
	private String dep_nameV = null;
	private String Sharing_nameV = null;

	private String branch_numberR = null;
	private String object_nameR = null;
	private String page_countR = null;
	private String sharingR = null;
	private String is_deletedR = null;
	private String status_nameR = null;
	private String cust_cif_numberR = null;
	private String cust_nameR = null;
	private String originalR = null;
	private String creator_codeR = null;
	private String dep_codeR = null;
	private String dep_nameR = null;
	private String sharing_nameR = null;
	private String cust_id_numberR = null;
	private String doc_nameR = null;
	private String creator_nameR = null;
	private String date_uploadR = null;
	private String doc_abbreviate_codeR = null;
	private String doc_abbreviate_group_codeR = null;
	private String doc_abbreviate_group_nameR = null;
	private String doc_abbreviate_nameR = null;
	private String doc_codeR = null;
	private String doc_subjectR = null;
	private String doc_upload_statusR = null;
	private String level_securityR = null;
	private String level_security_codeR = null;
	private String number_signR = null;
	private String type_doc_codeR = null;
	private String type_doc_nameR = null;
	private String file_typeR = null;

	private Statement accessStatementG;
	private Connection accessConnectionG;

	private SimulatedActivity activity;
	private int MAX = 0;
	private int current;
	private long WAIT = 1000;
	JButton rerunButtonV;
	JProgressBar jpb;
	Thread extractExportFailedDocsPBThread, extractExportFailedFolPBThread;

	/**
	 * Method Name : doExport Description : This will export documents into the
	 * documentum repository
	 * 
	 * @param destFolderPath
	 *            ,attributes,session
	 **/
	public String[] getBranchDetailsFromICDOCDB(Connection sqlConnectionBD) {
		LOGGER.debug("ExportToDocumentum  :: getBranchDetailsFromICDOCDB :: Enter into Method");
		String[] branchDetailsV = new String[2];
		Statement sqlSTMTBD = null;
		String branchDetailsQ = ICDOCBRANCHCODE;
		ResultSet sqlResultsetBD = null;
		String nameR = null, valueR = null;

		try {
			sqlSTMTBD = sqlConnectionBD.createStatement();
			sqlResultsetBD = sqlSTMTBD.executeQuery(branchDetailsQ);
			while (sqlResultsetBD.next()) {
				nameR = sqlResultsetBD.getString("Name");
				valueR = sqlResultsetBD.getString("Value");
				if (nameR.equalsIgnoreCase("Branch_Code")) {
					branchDetailsV[0] = valueR;
				} else if (nameR.equalsIgnoreCase("Branch")) {
					branchDetailsV[1] = valueR;
				}
			}
			LOGGER.debug("ExportToDocumentum  :: getBranchDetailsFromICDOCDB :: BranchCode=" + branchDetailsV[0] + ":: BranchName=" + branchDetailsV[1]);
		} catch (Exception e) {
			LOGGER.error("ExportToDocumentum  :: getBranchDetailsFromICDOCDB :: ED001" + e);
			JOptionPane.showMessageDialog(null, "MT00?-error occured in getBranchDetailsFromICDOCDB");
			e.printStackTrace();
		}
		LOGGER.debug("ExportToDocumentum  :: getBranchDetailsFromICDOCDB :: Exit from Method");
		return branchDetailsV;
	}

	/**
	 * Method Name : doExport Description : This will export documents into the
	 * documentum repository
	 * 
	 * @param destFolderPath
	 *            ,attributes,session
	 **/
	public Boolean prepareFolderStructure(HashMap prepareFolderAttributeHashMap, IDfSession session) throws DfException {
		LOGGER.debug("ExportToDocumentum  :: prepareFolderStructure :: Enter into Method");
		boolean folderStructureCreated = false;

		try {
			for (int i = 2010; i <= 2013; i++) {
				IDfSysObject idfParentFolderObj = (IDfSysObject) session.getObjectByPath("/" + (prepareFolderAttributeHashMap.get("BRANCH_CODE").toString()) + "/icDoc Docs/" + i);
				if (idfParentFolderObj == null) {
					IDfFolder icDocParentFolderObj = (IDfFolder) session.newObject(ICDOC_PARENT_FOLDER_TYPE);
					icDocParentFolderObj.link("/" + (prepareFolderAttributeHashMap.get("BRANCH_CODE").toString()) + "/" + IC_DOC_FOLDER_NAME);
					icDocParentFolderObj.setObjectName(Integer.toString(i));
					icDocParentFolderObj.save();
					folderStructureCreated = true;
				} else {
					LOGGER.debug("ExportToDocumentum  :: prepareFolderStructure :: " + i + " folder exist");
				}
			}

		} catch (Exception e) {

			LOGGER.error("ExportToDocumentum  :: prepareFolderStructure :: ED002" + e);
			JOptionPane.showMessageDialog(null, "MT00?-error occured in prepareFolderStructure");
			e.printStackTrace();
			folderStructureCreated = false;
		}
		LOGGER.debug("ExportToDocumentum  :: prepareFolderStructure :: Exit from Method");
		return folderStructureCreated;
	}

	/**
	 * Method Name : doExport Description : This will export documents into the
	 * documentum repository
	 * 
	 * @param destFolderPath
	 *            ,attributes,session
	 **/
	public String doCreateCustFolder(HashMap custFolderAttributeHashMap, IDfSession session, Statement sqlStatement, Statement accessStatement, Connection accessConnection,
			Connection sqlconnection) throws DfException {

		LOGGER.debug("ExportToDocumentum  :: doCreateCustFolder :: Enter into Method");
		accessConnectionG = accessConnection;
		accessStatementG = accessStatement;

		String exportMsg = "FAILED";
		String numberSign = custFolderAttributeHashMap.get("number_sign").toString();
		String[] yearValue = numberSign.split("/");

		try {
			String encryptedYear = ICDocEncryption.MD5(yearValue[2]);
			LOGGER.debug("ExportToDocumentum  :: doCreateCustFolder :: " + yearValue[2] + " encryptedYear" + encryptedYear);
			String sourceFolderPath = (custFolderAttributeHashMap.get("source_folder_path").toString()) + "\\" + encryptedYear;
			String destFolderPath = ("/Branch " + yearValue[0] + "/" + IC_DOC_FOLDER_NAME + "/" + yearValue[2] + "/" + numberSign.replaceAll("/", "-"));

			IDfSysObject idfcustFolderObj = (IDfSysObject) session.getObjectByPath("/Branch " + yearValue[0] + "/" + IC_DOC_FOLDER_NAME + "/" + yearValue[2] + "/"
					+ numberSign.replaceAll("/", "-"));
			if (idfcustFolderObj == null) {
				LOGGER.debug("ExportToDocumentum  :: doCreateCustFolder :: customer folder not exist creaitng new with: " + numberSign);
				String a = (custFolderAttributeHashMap.get("branch_number") == null) ? "" : "";
				IDfFolder icDocCustFolderObj = (IDfFolder) session.newObject(ICDOC_FOLDER_TYPE);
				icDocCustFolderObj.setString("branch_number", (custFolderAttributeHashMap.get("branch_number") == null) ? "" : custFolderAttributeHashMap.get("branch_number")
						.toString());
				icDocCustFolderObj.setString("code", (custFolderAttributeHashMap.get("code") == null) ? "" : custFolderAttributeHashMap.get("code").toString());
				icDocCustFolderObj.setString("folder_subject", (custFolderAttributeHashMap.get("folder_subject") == null) ? "" : custFolderAttributeHashMap.get("folder_subject")
						.toString());
				icDocCustFolderObj
						.setString("number_sign", (custFolderAttributeHashMap.get("number_sign") == null) ? "" : custFolderAttributeHashMap.get("number_sign").toString());
				icDocCustFolderObj.setString("creator_name", (custFolderAttributeHashMap.get("creator_name") == null) ? "" : custFolderAttributeHashMap.get("creator_name")
						.toString());
				icDocCustFolderObj.setString("verifier_name", (custFolderAttributeHashMap.get("verifier_name") == null) ? "" : custFolderAttributeHashMap.get("verifier_name")
						.toString());
				icDocCustFolderObj.setTime("date_enforce",
						new DfTime(((custFolderAttributeHashMap.get("date_enforce") == null) ? "" : custFolderAttributeHashMap.get("date_enforce").toString()), dateFormat));
				icDocCustFolderObj.setString("doc_abbreviate_name",
						(custFolderAttributeHashMap.get("doc_abbreviate_name") == null) ? "" : custFolderAttributeHashMap.get("doc_abbreviate_name").toString());
				icDocCustFolderObj
						.setString("type_detail", (custFolderAttributeHashMap.get("type_detail") == null) ? "" : custFolderAttributeHashMap.get("type_detail").toString());
				icDocCustFolderObj.setString("fa_cif", (custFolderAttributeHashMap.get("fa_cif") == null) ? "" : custFolderAttributeHashMap.get("fa_cif").toString());
				icDocCustFolderObj.setString("fa_id", (custFolderAttributeHashMap.get("fa_id") == null) ? "" : custFolderAttributeHashMap.get("fa_id").toString());
				icDocCustFolderObj.setString("fa_name", (custFolderAttributeHashMap.get("fa_name") == null) ? "" : custFolderAttributeHashMap.get("fa_name").toString());
				icDocCustFolderObj
						.setString("participate", (custFolderAttributeHashMap.get("participate") == null) ? "" : custFolderAttributeHashMap.get("participate").toString());
				icDocCustFolderObj
						.setString("status_name", (custFolderAttributeHashMap.get("status_name") == null) ? "" : custFolderAttributeHashMap.get("status_name").toString());
				icDocCustFolderObj.setString("original", (custFolderAttributeHashMap.get("original") == null) ? "" : custFolderAttributeHashMap.get("original").toString());
				icDocCustFolderObj.setString("specific_doc_name",
						(custFolderAttributeHashMap.get("specific_doc_name") == null) ? "" : custFolderAttributeHashMap.get("specific_doc_name").toString());
				icDocCustFolderObj.setString("tsdb_name", (custFolderAttributeHashMap.get("tsdb_name") == null) ? "" : custFolderAttributeHashMap.get("tsdb_name").toString());
				icDocCustFolderObj.setString("dep_name", (custFolderAttributeHashMap.get("dep_name") == null) ? "" : custFolderAttributeHashMap.get("dep_name").toString());
				icDocCustFolderObj
						.setString("dep_name_tw", (custFolderAttributeHashMap.get("dep_name_tw") == null) ? "" : custFolderAttributeHashMap.get("dep_name_tw").toString());
				icDocCustFolderObj.setString("name_group", (custFolderAttributeHashMap.get("name_group") == null) ? "" : custFolderAttributeHashMap.get("name_group").toString());
				icDocCustFolderObj.setString("code_group", (custFolderAttributeHashMap.get("code_group") == null) ? "" : custFolderAttributeHashMap.get("code_group").toString());
				icDocCustFolderObj
						.setString("status_code", (custFolderAttributeHashMap.get("status_code") == null) ? "" : custFolderAttributeHashMap.get("status_code").toString());
				icDocCustFolderObj.setString("doc_abbreviate_code",
						(custFolderAttributeHashMap.get("doc_abbreviate_code") == null) ? "" : custFolderAttributeHashMap.get("doc_abbreviate_code").toString());
				icDocCustFolderObj.setString("participate_code",
						(custFolderAttributeHashMap.get("participate_code") == null) ? "" : custFolderAttributeHashMap.get("participate_code").toString());
				icDocCustFolderObj.setString("field_action_code",
						(custFolderAttributeHashMap.get("field_action_code") == null) ? "" : custFolderAttributeHashMap.get("field_action_code").toString());
				icDocCustFolderObj.setString("tsdb_code", (custFolderAttributeHashMap.get("tsdb_code") == null) ? "" : custFolderAttributeHashMap.get("tsdb_code").toString());
				icDocCustFolderObj.setString("specific_doc_code",
						(custFolderAttributeHashMap.get("specific_doc_code") == null) ? "" : custFolderAttributeHashMap.get("specific_doc_code").toString());
				icDocCustFolderObj.setString("credit_council", (custFolderAttributeHashMap.get("credit_council") == null) ? "" : custFolderAttributeHashMap.get("credit_council")
						.toString());
				icDocCustFolderObj.link("/Branch " + yearValue[0] + "/" + IC_DOC_FOLDER_NAME + "/" + yearValue[2]);
				icDocCustFolderObj.setObjectName(numberSign.replaceAll("/", "-"));
				icDocCustFolderObj.save();

				ResultSet docResultSet = doExtractCustDocs(numberSign, sqlStatement);
				// call doExportICDOCDocs to export all documents belongs to
				// number sign folder by number sign
				doExportCustDocs(custFolderAttributeHashMap.get("number_sign").toString(), sourceFolderPath, destFolderPath, session, docResultSet, sqlconnection);
				exportMsg = "SUCCESS";

			} else {
				LOGGER.debug("ExportToDocumentum  :: doCreateCustFolder :: customer folder already with: " + numberSign);
				ResultSet docResultSet = doExtractCustDocs(numberSign, sqlStatement);
				// call doExportICDOCDocs to export all documents belongs to
				// number sign folder by number sign
				doExportCustDocs(custFolderAttributeHashMap.get("number_sign").toString(), sourceFolderPath, destFolderPath, session, docResultSet, sqlconnection);
				exportMsg = "SUCCESS";
			}

		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("ExportToDocumentum  :: doCreateCustFolder :: ED003" + e);
			e.printStackTrace();
			// JOptionPane.showMessageDialog(null,
			// "MT005-Error while export to ECM");
			exportMsg = "FAILED:FOLDER " + (e.toString()).replace("\"", "").replace("'", "");
		}
		LOGGER.debug("ExportToDocumentum  :: doCreateCustFolder :: Exit from Method");
		return exportMsg;
	}

	/**
	 * Method Name : doExport Description : This will export documents into the
	 * documentum repository
	 * 
	 * @param destFolderPath
	 *            ,attributes,session
	 **/
	public ResultSet doExtractCustDocs(String numberSign, Statement docsSTMT) throws DfException {
		ResultSet docsResultSet = null;
		try {
			LOGGER.debug("ExportToDocumentum  :: doExtractCustDocs :: Enter into Method");
			String extractsDocsQuery = (RSB.getString("ICDOCDOCSQUERY")) + "and a.[Number_Sign] = '" + numberSign + "' order by a.[code]";
			// String extractsDocsQuery =
			// "select * from Document_Detail where Number_Sign = '"+numberSign+"' order by Code";
			docsResultSet = docsSTMT.executeQuery(extractsDocsQuery);
		} catch (Exception e) {
			LOGGER.error("ExportToDocumentum  :: doExtractCustDocs :: ED004" + e);
			e.printStackTrace();
			// JOptionPane.showMessageDialog(null,
			// "MT005-Error while doExtractCustDocs from icdoc DB");
		}
		LOGGER.debug("ExportToDocumentum  :: doExtractCustDocs ::  Exit from Method");
		return docsResultSet;
	}

	/**
	 * Method Name : doExport Description : This will export documents into the
	 * documentum repository
	 * 
	 * @param destFolderPath
	 *            ,attributes,session
	 **/
	public Boolean doExportCustDocs(String numberSign, String sourceDocPath, String destDocPath, IDfSession session, ResultSet docResultSet, Connection sqlconnection)
			throws DfException {

		LOGGER.debug("ExportToDocumentum  :: doExportCustDocs :: Enter into Method");
		boolean exported = false;
		IDfId newSysObjId = null;
		IDfSysObject versionDoc = null;
		String[] yearValueDup = null;
		String encryptedYearDup = null;
		String encryptedYearUploadYearDup = null;
		String sourceDocPathDup = null;
		
		try {

			while (docResultSet.next()) {

				try {
					branch_number = docResultSet.getString("branch_number");
					object_name = docResultSet.getString("object_name");
					doc_name = docResultSet.getString("doc_name");
					doc_code = docResultSet.getString("doc_code");
					number_sign = docResultSet.getString("number_sign");
					doc_subject = docResultSet.getString("doc_subject");
					page_count = docResultSet.getString("page_count");
					doc_abbreviate_group_name = docResultSet.getString("doc_abbreviate_group_name");
					doc_abbreviate_name = docResultSet.getString("doc_abbreviate_name");
					type_doc_name = docResultSet.getString("type_doc_name");
					level_security = docResultSet.getString("level_security");
					date_upload = docResultSet.getString("date_upload");
					creator_name = docResultSet.getString("creator_name");
					type_doc_code = docResultSet.getString("type_doc_code");
					level_security_code = docResultSet.getString("level_security_code");
					doc_abbreviate_group_code = docResultSet.getString("doc_abbreviate_group_code");
					doc_abbreviate_code = docResultSet.getString("doc_abbreviate_code");
					sharing = docResultSet.getString("sharing");
					is_deleted = docResultSet.getString("is_deleted");
					file_type = docResultSet.getString("FileType");
					status_name = docResultSet.getString("status_name");
					cust_cif_number = docResultSet.getString("cust_cif_number");
					cust_id_number = docResultSet.getString("cust_id_number");
					cust_name = docResultSet.getString("cust_name");
					original = docResultSet.getString("original");
					creator_code = docResultSet.getString("creator_code");
					dep_code = docResultSet.getString("dep_code");
					dep_name = docResultSet.getString("dep_name");
					sharing_name = docResultSet.getString("sharing_name");

					IDfSysObject idfDocObj = (IDfSysObject) session.getObjectByQualification("vb_icdoc_docs where " + docCodeA + " ='" + doc_code + "' and " + NUMBER_SIGN + "='"
							+ numberSign + "'");// (destDocPath+"/"+docCode+"."+docFileType);
					if (idfDocObj == null) {
						String versionDocObjectId = extractAndExportAllVersionDocs(doc_code, number_sign, sourceDocPath, destDocPath, session, sqlconnection);
						if (versionDocObjectId == null || versionDocObjectId=="") {
							LOGGER.debug("Version Doc Not Exist, creation new document with version 1.0****");
							IDfSysObject icDocDocumentObj = (IDfSysObject) session.newObject(ICDOCDOCTYPE);
							icDocDocumentObj.setString("branch_number", branch_number);
							icDocDocumentObj.setString("doc_name", doc_name);
							icDocDocumentObj.setString("doc_code", doc_code);
							icDocDocumentObj.setString("number_sign", number_sign);
							icDocDocumentObj.setString("page_count", page_count);
							icDocDocumentObj.setString("doc_subject", doc_subject);
							icDocDocumentObj.setString("doc_abbreviate_group_name", doc_abbreviate_group_name);
							icDocDocumentObj.setString("doc_abbreviate_name", doc_abbreviate_name);
							icDocDocumentObj.setString("type_doc_name", type_doc_name);
							icDocDocumentObj.setString("level_security", level_security);
							icDocDocumentObj.setTime("date_upload", new DfTime(date_upload, dateFormat));
							icDocDocumentObj.setString("creator_name", creator_name);
							icDocDocumentObj.setString("type_doc_code", type_doc_code);
							icDocDocumentObj.setString("level_security_code", level_security_code);
							icDocDocumentObj.setString("doc_abbreviate_group_code", doc_abbreviate_group_code);
							icDocDocumentObj.setString("doc_abbreviate_code", doc_abbreviate_code);
							icDocDocumentObj.setString("sharing", sharing);
							icDocDocumentObj.setString("is_deleted", is_deleted);
							icDocDocumentObj.setString("status_name", status_name);
							icDocDocumentObj.setString("cust_cif_number", cust_cif_number);
							icDocDocumentObj.setString("cust_id_number", cust_id_number);
							icDocDocumentObj.setString("cust_name", cust_name);
							icDocDocumentObj.setString("original", original);
							icDocDocumentObj.setString("creator_code", creator_code);
							icDocDocumentObj.setString("dep_code", dep_code);
							icDocDocumentObj.setString("dep_name", dep_name);
							icDocDocumentObj.setString("sharing_name", sharing_name);
							//LOGGER.debug("ExportToDocumentum  :: doExportCustDocs ::  SourceDocPath:" + sourceDocPath + "/" + doc_code + "." + file_type);
							//LOGGER.debug("ExportToDocumentum  :: doExportCustDocs ::  DestinationDocPath:" + destDocPath);
							icDocDocumentObj.setObjectName(object_name);
							icDocDocumentObj.setContentType(RSB.getString(file_type.toLowerCase()));
							icDocDocumentObj.setTitle("Migration Tool");
							yearValueDup = number_sign.split("/");
							encryptedYearDup = ICDocEncryption.MD5(yearValueDup[2]);
							LOGGER.debug("encryptedYearDup"+encryptedYearDup);
							encryptedYearUploadYearDup = ICDocEncryption.MD5(date_upload.substring(6, 10));
							LOGGER.debug("date_upload"+date_upload);
							LOGGER.debug("encryptedYearUploadYearDup"+encryptedYearUploadYearDup);
							LOGGER.debug("sourceDocPath"+sourceDocPath);
							sourceDocPathDup = sourceDocPath.replaceAll(encryptedYearDup, encryptedYearUploadYearDup);
							LOGGER.debug("sourceDocPathDup"+sourceDocPathDup);							
							icDocDocumentObj.setFile(sourceDocPathDup + "\\" + doc_name);
							icDocDocumentObj.link(destDocPath);
							icDocDocumentObj.save();

							// Update into Access Database Document Details
							// Table
							accessDatabase2.insertExportedDocsIntoAccessDB(doc_code, numberSign, icDocDocumentObj.getObjectId().getId(), Calendar.getInstance().getTime()
									.toString(), "SUCCESS", accessStatementG);
							accessConnectionG.commit();
						} else {
							LOGGER.debug("Version Doc Exist, Creted, Making this as current version***");
							versionDoc = (IDfSysObject)session.getObject(new DfId(versionDocObjectId));
							if (!versionDoc.isCheckedOut()) {
								LOGGER.debug("before checkout***");
								versionDoc.checkout();
								LOGGER.debug("after checkout***");
							} else {
								versionDoc.cancelCheckout();
								versionDoc.checkout();
							}
							versionDoc.setString("branch_number", branch_number);
							versionDoc.setString("doc_name", doc_name);
							versionDoc.setString("doc_code", doc_code);
							versionDoc.setString("number_sign", number_sign);
							versionDoc.setString("page_count", page_count);
							versionDoc.setString("doc_subject", doc_subject);
							versionDoc.setString("doc_abbreviate_group_name", doc_abbreviate_group_name);
							versionDoc.setString("doc_abbreviate_name", doc_abbreviate_name);
							versionDoc.setString("type_doc_name", type_doc_name);
							versionDoc.setString("level_security", level_security);
							versionDoc.setTime("date_upload", new DfTime(date_upload, dateFormat));
							versionDoc.setString("creator_name", creator_name);
							versionDoc.setString("type_doc_code", type_doc_code);
							versionDoc.setString("level_security_code", level_security_code);
							versionDoc.setString("doc_abbreviate_group_code", doc_abbreviate_group_code);
							versionDoc.setString("doc_abbreviate_code", doc_abbreviate_code);
							versionDoc.setString("sharing", sharing);
							versionDoc.setString("is_deleted", is_deleted);
							versionDoc.setString("status_name", status_name);
							versionDoc.setString("cust_cif_number", cust_cif_number);
							versionDoc.setString("cust_id_number", cust_id_number);
							versionDoc.setString("cust_name", cust_name);
							versionDoc.setString("original", original);
							versionDoc.setString("creator_code", creator_code);
							versionDoc.setString("dep_code", dep_code);
							versionDoc.setString("dep_name", dep_name);
							versionDoc.setString("sharing_name", sharing_name);
							//LOGGER.debug("ExportToDocumentum  :: doExportCustDocs ::  SourceDocPath:" + sourceDocPath + "/" + doc_code + "." + file_type);
							//LOGGER.debug("ExportToDocumentum  :: doExportCustDocs ::  DestinationDocPath:" + destDocPath);
							versionDoc.setObjectName(object_name);
							versionDoc.setContentType(RSB.getString(file_type.toLowerCase()));
							versionDoc.setTitle("Migration Tool- Exist and versioning");
							yearValueDup = number_sign.split("/");
							encryptedYearDup = ICDocEncryption.MD5(yearValueDup[2]);
							LOGGER.debug("encryptedYearDup"+encryptedYearDup);
							encryptedYearUploadYearDup = ICDocEncryption.MD5(date_upload.substring(6, 10));
							LOGGER.debug("date_upload"+date_upload);
							LOGGER.debug("encryptedYearUploadYearDup"+encryptedYearUploadYearDup);
							LOGGER.debug("sourceDocPath"+sourceDocPath);
							sourceDocPathDup = sourceDocPath.replaceAll(encryptedYearDup, encryptedYearUploadYearDup);
							LOGGER.debug("sourceDocPathDup"+sourceDocPathDup);
							versionDoc.setFile(sourceDocPathDup + "\\" + doc_name);
							// versionDoc.link(destDocPath);
							newSysObjId = versionDoc.checkin(false, "");
							// versionDoc.save();
							// Update into Access Database Document Details
							// Table
							accessDatabase2.insertExportedDocsIntoAccessDB(doc_code, numberSign, newSysObjId.toString(), Calendar.getInstance().getTime().toString(), "SUCCESS",
									accessStatementG);
							accessConnectionG.commit();
						}

					} else {
						LOGGER.debug("ExportToDocumentum  :: doExportCustDocs :: Document already exist with Code=" + doc_code + " and Number Sign=" + numberSign);
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					// Update into Access Database Document Details Table
					LOGGER.error("ExportToDocumentum  :: doExportCustDocs :: ED005" + e);
					e.printStackTrace();
					LOGGER.debug("ExportToDocumentum  :: doExportCustDocs :: ExportToDocumentum  :: doExportCustDocs :: " + (e.toString()).replace("\"", "").replace("'", ""));
					accessDatabase2.insertExportedDocsIntoAccessDB(doc_code, numberSign, "0000000000000000", Calendar.getInstance().getTime().toString(),
							"FAILED: " + (e.toString()).replace("\"", "").replace("'", ""), accessStatementG);
					accessConnectionG.commit();
					// e.printStackTrace();
				}

			}
		} catch (Exception e) {
			// JOptionPane.showMessageDialog(null,
			// "MT005-Error doExportCustDocs");
			LOGGER.error("ExportToDocumentum  :: doExportCustDocs :: ED006" + e);
			e.printStackTrace();
			exported = false;
		}
		LOGGER.debug("ExportToDocumentum  :: doExportCustDocs :: Exit from Method");
		return exported;
	}

	/*
	 * Extract and export version documents related to Number Sign
	 */
	public String extractAndExportAllVersionDocs(String docCodeV, String numberSignV, String sourcePathV, String destpathV, IDfSession sessionV, Connection sqlconnection) {
		LOGGER.debug("ExportToDocumentum  :: extractAndExportAllVersionDocs :: Enter into Method");
		String extractsVersionDocsQuery = (RSB.getString("ICDOCVERSIONDOCSQUERY")) + "and a.[number_sign] = '" + numberSignV + "' and a.[code] = '" + docCodeV
				+ "'  order by z.code";
		LOGGER.debug("ExportToDocumentum  :: extractAndExportAllVersionDocs ::extractsVersionDocsQuery" + extractsVersionDocsQuery);
		LOGGER.debug("ExportToDocumentum  :: extractAndExportAllVersionDocs ::extractsVersionDocsQuery:" + "and a.[number_sign] = '" + numberSignV + "' and a.[code] = '" + docCodeV
				+ "'  order by z.code");
		IDfSysObject icDocDocumentObj = null;
		IDfSysObject versionDoc2 = null;
		IDfId newVesionSysObjId = null;
		String returnString = null;
		String objectQualification = null;
		IDfCollection coll = null;
		String objectIdStr = null;
		String[] yearValueDup = null;
		String encryptedYearDup = null;
		String encryptedYearUploadYearDup = null;
		String sourceDocPathDup = null;
		try {
			IDfClientX clientX =  new DfClientX();
			IDfQuery query = clientX.getQuery(); 
			Statement sqlStatementV = sqlconnection.createStatement();
			ResultSet versionDocsResultSet = sqlStatementV.executeQuery(extractsVersionDocsQuery);

			while (versionDocsResultSet.next()) {
				
				branch_numberV = versionDocsResultSet.getString("branch_number");
				object_nameV = versionDocsResultSet.getString("object_name");
				doc_nameV = versionDocsResultSet.getString("doc_name");
				doc_codeV = versionDocsResultSet.getString("doc_code");
				number_signV = versionDocsResultSet.getString("number_sign");
				doc_subjectV = versionDocsResultSet.getString("doc_subject");
				page_countV = versionDocsResultSet.getString("page_count");
				doc_abbreviate_group_nameV = versionDocsResultSet.getString("doc_abbreviate_group_name");
				doc_abbreviate_nameV = versionDocsResultSet.getString("doc_abbreviate_name");
				type_doc_nameV = versionDocsResultSet.getString("type_doc_name");
				level_securityV = versionDocsResultSet.getString("level_security");
				date_uploadV = versionDocsResultSet.getString("date_upload");
				creator_nameV = versionDocsResultSet.getString("creator_name");
				type_doc_codeV = versionDocsResultSet.getString("type_doc_code");
				level_security_codeV = versionDocsResultSet.getString("level_security_code");
				doc_abbreviate_group_codeV = versionDocsResultSet.getString("doc_abbreviate_group_code");
				doc_abbreviate_codeV = versionDocsResultSet.getString("doc_abbreviate_code");
				sharingV = versionDocsResultSet.getString("sharing");
				is_deletedV = versionDocsResultSet.getString("is_deleted");
				file_typeV = versionDocsResultSet.getString("FileType");
				status_nameV = versionDocsResultSet.getString("status_name");
				cust_cif_numberV = versionDocsResultSet.getString("cust_cif_number");
				cust_id_numberV = versionDocsResultSet.getString("cust_id_number");
				cust_nameV = versionDocsResultSet.getString("cust_name");
				originalV = versionDocsResultSet.getString("original");
				creator_codeV = versionDocsResultSet.getString("creator_code");
				dep_codeV = versionDocsResultSet.getString("dep_code");
				dep_nameV = versionDocsResultSet.getString("dep_name");
				Sharing_nameV = versionDocsResultSet.getString("Sharing_name");
				objectQualification = "select * from vb_icdoc_docs where " + docCodeA + " like '" + doc_codeV.substring(0, 4) + "_%' and " + NUMBER_SIGN
						+ "='" + numberSignV + "' order by r_object_id";
				LOGGER.debug("objectQualification:"+objectQualification);
				//icDocDocumentObj = (IDfSysObject) session.getObjectByQualification(objectQualification);
				
				//Query to check whether docs are exist or not
				query.setDQL(objectQualification);				
				coll =  query.execute(session, IDfQuery.DF_READ_QUERY);					
				while(coll.next()){	
					objectIdStr= coll.getString("r_object_id");
				}
								
				if (objectIdStr == null || objectIdStr=="") {
					LOGGER.debug("Version Not Exist, creating initial version*");
					icDocDocumentObj = (IDfSysObject) session.newObject(ICDOCDOCTYPE);
					icDocDocumentObj.setString("branch_number", branch_numberV);
					icDocDocumentObj.setString("doc_name", doc_nameV);
					icDocDocumentObj.setString("doc_code", doc_codeV);
					icDocDocumentObj.setString("number_sign", number_signV);
					icDocDocumentObj.setString("doc_subject", doc_subjectV);
					icDocDocumentObj.setString("page_count", page_countV);
					icDocDocumentObj.setString("doc_abbreviate_group_name", doc_abbreviate_group_nameV);
					icDocDocumentObj.setString("doc_abbreviate_name", doc_abbreviate_nameV);
					icDocDocumentObj.setString("type_doc_name", type_doc_nameV);
					icDocDocumentObj.setString("level_security", level_securityV);
					icDocDocumentObj.setTime("date_upload", new DfTime(date_uploadV, dateFormat));
					icDocDocumentObj.setString("creator_name", creator_nameV);
					icDocDocumentObj.setString("type_doc_code", type_doc_codeV);
					icDocDocumentObj.setString("level_security_code", level_security_codeV);
					icDocDocumentObj.setString("doc_abbreviate_group_code", doc_abbreviate_group_codeV);
					icDocDocumentObj.setString("doc_abbreviate_code", doc_abbreviate_codeV);
					icDocDocumentObj.setString("sharing", sharingV);
					icDocDocumentObj.setString("is_deleted", is_deletedV);
					icDocDocumentObj.setString("status_name", status_nameV);
					icDocDocumentObj.setString("cust_cif_number", cust_cif_numberV);
					icDocDocumentObj.setString("cust_id_number", cust_id_numberV);
					icDocDocumentObj.setString("cust_name", cust_nameV);
					icDocDocumentObj.setString("original", originalV);
					icDocDocumentObj.setString("creator_code", creator_codeV);
					icDocDocumentObj.setString("dep_code", dep_codeV);
					icDocDocumentObj.setString("dep_name", dep_nameV);
					icDocDocumentObj.setString("sharing_name", Sharing_nameV);
					//LOGGER.debug("ExportToDocumentum  :: extractAndExportAllVersionDocs ::  SourceDocPath:" + sourcePathV + "/" + doc_codeV + "." + file_typeV);
					//LOGGER.debug("ExportToDocumentum  :: extractAndExportAllVersionDocs ::  DestinationDocPath:" + destpathV);
					icDocDocumentObj.setObjectName(object_nameV);
					icDocDocumentObj.setContentType(RSB.getString(file_typeV.toLowerCase()));
					icDocDocumentObj.setTitle("Migration Tool-Initial Doc");
					yearValueDup = number_signV.split("/");
					encryptedYearDup = ICDocEncryption.MD5(yearValueDup[2]);
					LOGGER.debug("encryptedYearDup"+encryptedYearDup);
					encryptedYearUploadYearDup = ICDocEncryption.MD5(date_uploadV.substring(6, 10));
					LOGGER.debug("date_uploadV"+date_uploadV);
					LOGGER.debug("encryptedYearUploadYearDup"+encryptedYearUploadYearDup);
					LOGGER.debug("sourceDocPath"+sourcePathV);
					sourceDocPathDup = sourcePathV.replaceAll(encryptedYearDup, encryptedYearUploadYearDup);
					LOGGER.debug("sourceDocPathDup"+sourceDocPathDup);
					icDocDocumentObj.setFile(sourceDocPathDup + "\\" + doc_nameV);
					icDocDocumentObj.link(destpathV);
					icDocDocumentObj.save();
					accessDatabase2.insertExportedDocsIntoAccessDB(doc_codeV, number_signV, icDocDocumentObj.getObjectId().getId(), Calendar.getInstance().getTime().toString(),
							"SUCCESS", accessStatementG);
					accessConnectionG.commit();
					returnString = icDocDocumentObj.getObjectId().getId();
				} else {
					LOGGER.debug("Version Exist, creating version docs **");
					versionDoc2 = (IDfSysObject)session.getObject(new DfId(objectIdStr));
					if (!versionDoc2.isCheckedOut()) {
						LOGGER.debug("before checkout**");
						versionDoc2.checkout();
						LOGGER.debug("after checkout**");
					} else {
						versionDoc2.cancelCheckout();
						versionDoc2.checkout();
					}
					versionDoc2.setString("branch_number", branch_numberV);
					versionDoc2.setString("doc_name", doc_nameV);
					versionDoc2.setString("doc_code", doc_codeV);
					versionDoc2.setString("number_sign", number_signV);
					versionDoc2.setString("doc_subject", doc_subjectV);
					versionDoc2.setString("page_count", page_countV);
					versionDoc2.setString("doc_abbreviate_group_name", doc_abbreviate_group_nameV);
					versionDoc2.setString("doc_abbreviate_name", doc_abbreviate_nameV);
					versionDoc2.setString("type_doc_name", type_doc_nameV);
					versionDoc2.setString("level_security", level_securityV);
					versionDoc2.setTime("date_upload", new DfTime(date_uploadV, dateFormat));
					versionDoc2.setString("creator_name", creator_nameV);
					versionDoc2.setString("type_doc_code", type_doc_codeV);
					versionDoc2.setString("level_security_code", level_security_codeV);
					versionDoc2.setString("doc_abbreviate_group_code", doc_abbreviate_group_codeV);
					versionDoc2.setString("doc_abbreviate_code", doc_abbreviate_codeV);
					versionDoc2.setString("sharing", sharingV);
					versionDoc2.setString("is_deleted", is_deletedV);
					versionDoc2.setString("status_name", status_nameV);
					versionDoc2.setString("cust_cif_number", cust_cif_numberV);
					versionDoc2.setString("cust_id_number", cust_id_numberV);
					versionDoc2.setString("cust_name", cust_nameV);
					versionDoc2.setString("original", originalV);
					versionDoc2.setString("creator_code", creator_codeV);
					versionDoc2.setString("dep_code", dep_codeV);
					versionDoc2.setString("dep_name", dep_nameV);
					versionDoc2.setString("sharing_name", Sharing_nameV);
					//LOGGER.debug("ExportToDocumentum  :: extractAndExportAllVersionDocs ::  SourceDocPath:" + sourcePathV + "/" + doc_codeV + "." + file_typeV);
					//LOGGER.debug("ExportToDocumentum  :: extractAndExportAllVersionDocs ::  DestinationDocPath:" + destpathV);
					versionDoc2.setObjectName(object_nameV);
					versionDoc2.setContentType(RSB.getString(file_typeV.toLowerCase()));
					versionDoc2.setTitle("Migration Tool-Version Doc");
					yearValueDup = number_signV.split("/");
					encryptedYearDup = ICDocEncryption.MD5(yearValueDup[2]);
					LOGGER.debug("encryptedYearDup"+encryptedYearDup);
					encryptedYearUploadYearDup = ICDocEncryption.MD5(date_uploadV.substring(6, 10));
					LOGGER.debug("date_uploadV"+date_uploadV);
					LOGGER.debug("encryptedYearUploadYearDup"+encryptedYearUploadYearDup);
					LOGGER.debug("sourceDocPath"+sourcePathV);
					sourceDocPathDup = sourcePathV.replaceAll(encryptedYearDup, encryptedYearUploadYearDup);
					LOGGER.debug("sourceDocPathDup"+sourceDocPathDup);
					versionDoc2.setFile(sourceDocPathDup + "\\" + doc_nameV);
					// icDocDocumentObj.link(destpathV);
					newVesionSysObjId = versionDoc2.checkin(false, "");
					// idfDocObj.save();
					accessDatabase2.insertExportedDocsIntoAccessDB(doc_codeV, number_signV, newVesionSysObjId.toString(), Calendar.getInstance().getTime().toString(), "SUCCESS",
							accessStatementG);
					accessConnectionG.commit();
					returnString = newVesionSysObjId.getId();
					// LOGGER.debug("ExportToDocumentum  :: extractAndExportAllVersionDocs :: Document already exist with Code="+doc_codeV+" and Number Sign="+numberSignV);
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			LOGGER.error("ExportToDocumentum  :: extractAndExportAllVersionDocs :: ED007" + e);
			try {
				accessDatabase2.insertExportedDocsIntoAccessDB(doc_codeV, number_signV, "0000000000000000", Calendar.getInstance().getTime().toString(),
						"FAILED: V-" + (e.toString()).replace("\"", "").replace("'", ""), accessStatementG);
				accessConnectionG.commit();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		} catch (DfException e) {
			// TODO Auto-generated catch block
			LOGGER.error("ExportToDocumentum  :: extractAndExportAllVersionDocs :: ED008" + e);
			try {
				accessDatabase2.insertExportedDocsIntoAccessDB(doc_codeV, number_signV, "0000000000000000", Calendar.getInstance().getTime().toString(),
						"FAILED: V-" + (e.toString()).replace("\"", "").replace("'", ""), accessStatementG);
				accessConnectionG.commit();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();

		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(coll != null) {
				try {
					coll.close();
				} catch (DfException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
		LOGGER.debug("ExportToDocumentum  :: extractAndExportAllVersionDocs :: Exit from Method");
		return returnString;
	}

	public void doExportFailedCustDocs(Connection sqlConn, String sourceFolderPath, String branchCode, JProgressBar progressBar, JButton rerunButton, Connection accConn) {
		LOGGER.debug("ExportToDocumentum  :: doExportFailedCustDocs :: Enter into Method");
		try {
			ResultSet failedDocsResultSetSQL = null;
			String extractsFailedDocsQuery = null;
			String destFolderPath = null;
			jpb = progressBar;
			rerunButtonV = rerunButton;
			int failedDocCount = 0;
			String[] yearValue;
			String encryptedYear;
			String[] yearValueDup = null;
			String encryptedYearDup = null;
			String encryptedYearUploadYearDup = null;
			String sourceDocPathDup = null;
			Statement selectAccessDataSTMT = accConn.createStatement();
			Statement updateAccessDataSTMT = accConn.createStatement();
			Statement sqlStatementFailedDocs = sqlConn.createStatement();
			// Statement sqlStatementFailedVersionDocs =
			// sqlConn.createStatement();
			String selectFailedDataCount = "select count(*) as totalFailedDocs from icdocdocuments where Object_Id ='0000000000000000'";
			ResultSet selectFailedDataCountResultSet = selectAccessDataSTMT.executeQuery(selectFailedDataCount);
			while (selectFailedDataCountResultSet.next()) {
				failedDocCount = selectFailedDataCountResultSet.getInt("totalFailedDocs");
				MAX = failedDocCount;
			}
			if (failedDocCount <= 0) {
				JOptionPane.showMessageDialog(null, "MT00X-No failed records found !");
				return;
			}

			jpb.setMinimum(0);
			jpb.setMaximum(MAX);
			long startTime = 0;

			String selectFailedData = "select * from icdocdocuments where Object_Id ='0000000000000000'";
			ResultSet selectFailedDataResultSet = selectAccessDataSTMT.executeQuery(selectFailedData);
			String documentCode, numberSign, ObjectId, exportDate, exportStatus;
			extractExportFailedDocsPBThread = new Thread(extractExportFailedDocsPBRnnable);
			extractExportFailedDocsPBThread.start();
			while (selectFailedDataResultSet.next()) {

				startTime = System.currentTimeMillis();
				documentCode = selectFailedDataResultSet.getString("Document_Code");
				numberSign = selectFailedDataResultSet.getString("Number_Sign");
				ObjectId = selectFailedDataResultSet.getString("Object_Id");
				exportDate = selectFailedDataResultSet.getString("Export_Date");
				exportStatus = selectFailedDataResultSet.getString("Export_Status");

				if (documentCode.contains("_")) {
					extractsFailedDocsQuery = RSB.getString("ICDOCVERSIONDOCSQUERY") + "and a.[number_sign] = '" + numberSign + "' and z.JoinCode = '" + documentCode + "' ";
					LOGGER.debug("extractsVersionDocsQuery:" + extractsFailedDocsQuery);
				} else {
					extractsFailedDocsQuery = RSB.getString("ICDOCDOCSQUERY") + "and a.[Number_Sign] = '" + numberSign + "' and a.[Code]= '" + documentCode + "' ";
					LOGGER.debug("extractsDocsQuery:" + extractsFailedDocsQuery);
				}

				failedDocsResultSetSQL = sqlStatementFailedDocs.executeQuery(extractsFailedDocsQuery);
				yearValue = numberSign.split("/");
				destFolderPath = ("/" + branchCode + "/" + IC_DOC_FOLDER_NAME + "/" + yearValue[2] + "/" + numberSign.replaceAll("/", "-"));
				isCustFolderExist(destFolderPath, numberSign);
				encryptedYear = ICDocEncryption.MD5(yearValue[2]);

				try {
					IDfSysObject idfDocObj = (IDfSysObject) session.getObjectByQualification("vb_icdoc_docs where " + docCodeA + " ='" + documentCode + "' and " + NUMBER_SIGN
							+ "='" + numberSign + "'");// (destDocPath+"/"+docCode+"."+docFileType);
					if (idfDocObj == null) {
						while (failedDocsResultSetSQL.next()) {

							branch_numberR = failedDocsResultSetSQL.getString("branch_number");
							object_nameR = failedDocsResultSetSQL.getString("object_name");
							doc_nameR = failedDocsResultSetSQL.getString("doc_name");
							doc_codeR = failedDocsResultSetSQL.getString("doc_code");
							number_signR = failedDocsResultSetSQL.getString("number_sign");
							doc_subjectR = failedDocsResultSetSQL.getString("doc_subject");
							page_countR = failedDocsResultSetSQL.getString("page_count");
							doc_abbreviate_group_nameR = failedDocsResultSetSQL.getString("doc_abbreviate_group_name");
							doc_abbreviate_nameR = failedDocsResultSetSQL.getString("doc_abbreviate_name");
							type_doc_nameR = failedDocsResultSetSQL.getString("type_doc_name");
							level_securityR = failedDocsResultSetSQL.getString("level_security");
							date_uploadR = failedDocsResultSetSQL.getString("date_upload");
							creator_nameR = failedDocsResultSetSQL.getString("creator_name");
							type_doc_codeR = failedDocsResultSetSQL.getString("type_doc_code");
							level_security_codeR = failedDocsResultSetSQL.getString("level_security_code");
							doc_abbreviate_group_codeR = failedDocsResultSetSQL.getString("doc_abbreviate_group_code");
							doc_abbreviate_codeR = failedDocsResultSetSQL.getString("doc_abbreviate_code");
							sharingR = failedDocsResultSetSQL.getString("sharing");
							is_deletedR = failedDocsResultSetSQL.getString("is_deleted");
							file_typeR = failedDocsResultSetSQL.getString("FileType");
							status_nameR = failedDocsResultSetSQL.getString("status_name");
							cust_cif_numberR = failedDocsResultSetSQL.getString("cust_cif_number");
							cust_id_numberR = failedDocsResultSetSQL.getString("cust_id_number");
							cust_nameR = failedDocsResultSetSQL.getString("cust_name");
							originalR = failedDocsResultSetSQL.getString("original");
							creator_codeR = failedDocsResultSetSQL.getString("creator_code");
							dep_codeR = failedDocsResultSetSQL.getString("dep_code");
							dep_nameR = failedDocsResultSetSQL.getString("dep_name");
							sharing_nameR = failedDocsResultSetSQL.getString("sharing_name");

							IDfSysObject icDocDocumentObj = (IDfSysObject) session.newObject(ICDOCDOCTYPE);
							icDocDocumentObj.setString("branch_number", branch_numberR);
							icDocDocumentObj.setString("doc_name", doc_nameR);
							icDocDocumentObj.setString("doc_code", doc_codeR);
							icDocDocumentObj.setString("number_sign", number_signR);
							icDocDocumentObj.setString("doc_subject", doc_subjectR);
							icDocDocumentObj.setString("page_count", page_countR);
							icDocDocumentObj.setString("doc_abbreviate_group_name", doc_abbreviate_group_nameR);
							icDocDocumentObj.setString("doc_abbreviate_name", doc_abbreviate_nameR);
							icDocDocumentObj.setString("type_doc_name", type_doc_nameR);
							icDocDocumentObj.setString("level_security", level_securityR);
							icDocDocumentObj.setTime("date_upload", new DfTime(date_uploadR, dateFormat));
							icDocDocumentObj.setString("creator_name", creator_nameR);
							icDocDocumentObj.setString("type_doc_code", type_doc_codeR);
							icDocDocumentObj.setString("level_security_code", level_security_codeR);
							icDocDocumentObj.setString("doc_abbreviate_group_code", doc_abbreviate_group_codeR);
							icDocDocumentObj.setString("doc_abbreviate_code", doc_abbreviate_codeR);
							icDocDocumentObj.setString("sharing", sharingR);
							icDocDocumentObj.setString("is_deleted", is_deletedR);
							icDocDocumentObj.setString("status_name", status_nameR);
							icDocDocumentObj.setString("cust_cif_number", cust_cif_numberR);
							icDocDocumentObj.setString("cust_id_number", cust_id_numberR);
							icDocDocumentObj.setString("cust_name", cust_nameR);
							icDocDocumentObj.setString("original", originalR);
							icDocDocumentObj.setString("creator_code", creator_codeR);
							icDocDocumentObj.setString("dep_code", dep_codeR);
							icDocDocumentObj.setString("dep_name", dep_nameR);
							icDocDocumentObj.setString("sharing_name", sharing_nameR);
							icDocDocumentObj.setObjectName(object_nameR);
							LOGGER.debug("ExportToDocumentum  :: doExportFailedCustDocs ::  SourceDocPath:" + sourceFolderPath + "/" + encryptedYear + "/" + doc_codeR + "."
									+ file_type);
							LOGGER.debug("ExportToDocumentum  :: doExportFailedCustDocs ::  DestinationDocPath:" + destFolderPath);
							icDocDocumentObj.setTitle("Migration Tool-Rerun");
							icDocDocumentObj.setContentType(RSB.getString(file_typeR.toLowerCase()));
							yearValueDup = number_signR.split("/");
							encryptedYearDup = ICDocEncryption.MD5(yearValueDup[2]);
							LOGGER.debug("encryptedYearDup"+encryptedYearDup);
							encryptedYearUploadYearDup = ICDocEncryption.MD5(date_uploadR.substring(6, 10));
							LOGGER.debug("date_uploadR"+date_uploadR);
							LOGGER.debug("encryptedYearUploadYearDup"+encryptedYearUploadYearDup);
							LOGGER.debug("sourceDocPath"+sourceFolderPath);
							sourceDocPathDup = sourceFolderPath.replaceAll(encryptedYearDup, encryptedYearUploadYearDup);
							LOGGER.debug("sourceDocPathDup"+sourceDocPathDup);
							//icDocDocumentObj.setFile(sourceFolderPath + "\\" + encryptedYear + "\\" + doc_nameR);
							icDocDocumentObj.setFile(sourceFolderPath + "\\" + encryptedYearUploadYearDup + "\\" + doc_nameR);
							icDocDocumentObj.link(destFolderPath);
							// extractAndExportAllVersionDocs(doc_codeR,
							// numberSign, sourceFolderPath+"\\"+encryptedYear,
							// destFolderPath, session, sqlConn);
							icDocDocumentObj.save();

							// Update into Access Database Document Details
							// Table
							accessDatabase2.updateExportedDocsIntoAccessDB(documentCode, numberSign, icDocDocumentObj.getObjectId().getId(), Calendar.getInstance().getTime()
									.toString(), "SUCCESS", updateAccessDataSTMT);
							accConn.commit();

						}

					} else {
						LOGGER.debug("ExportToDocumentum  :: doExportFailedCustDocs :: Document already exist with Code=" + documentCode + " and Number Sign=" + numberSign);
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					LOGGER.error("ExportToDocumentum  :: doExportFailedCustDocs :: ED008" + e);
					e.printStackTrace();
					// Update into Access Database Document Details Table
					accessDatabase2.updateExportedDocsIntoAccessDB(documentCode, numberSign, ObjectId, Calendar.getInstance().getTime().toString(), "FAILED: "
							+ (e.toString()).replace("\"", "").replace("'", ""), updateAccessDataSTMT);
					accConn.commit();
				}
				current++;
				WAIT = (System.currentTimeMillis()) - startTime;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			LOGGER.error("ExportToDocumentum  :: doExportFailedCustDocs :: ED009" + e);
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			LOGGER.error("ExportToDocumentum  :: doExportFailedCustDocs :: ED010" + e);
			e.printStackTrace();
		} finally {
			LOGGER.debug("ExportToDocumentum  :: doExportFailedCustDocs :: Exit from Method");
		}
	}

	
	public void doExportFailedCustFolders(IDfSession sessionF, Connection sqlConn, Connection accConn, Statement stmt3, Statement accessstmt4, String sourceFolderPath, String branchCode, JProgressBar progressBar, JButton rerunButton) {
		LOGGER.debug("ExportToDocumentum  :: doExportFailedCustDocs :: Enter into Method");
		try {
			ResultSet failedDocsResultSetSQL = null;
			String extractsFailedDocsQuery = null;
			String destFolderPath = null;
			jpb = progressBar;
			rerunButtonV = rerunButton;
			int failedDocCount = 0;
			String[] yearValue;
			String encryptedYear;
			Statement selectAccessDataSTMT = accConn.createStatement();
			Statement updateAccessDataSTMT = accConn.createStatement();
			Statement sqlStatementFailedFol = sqlConn.createStatement();
			// Statement sqlStatementFailedVersionDocs =
			// sqlConn.createStatement();
			String selectFailedFolCount = "select count(*) as totalFailedFolders from icdocfolders where Export_Status <>'SUCCESS'";
			LOGGER.debug("selectFailedFolCount:"+selectFailedFolCount);
			ResultSet selectFailedFolCountResultSet = selectAccessDataSTMT.executeQuery(selectFailedFolCount);
			while (selectFailedFolCountResultSet.next()) {
				failedDocCount = selectFailedFolCountResultSet.getInt("totalFailedFolders");
				MAX = failedDocCount;
			}
			if (failedDocCount <= 0) {
				JOptionPane.showMessageDialog(null, "MT00X-No failed folder found !");
				return;
			}

			jpb.setMinimum(0);
			jpb.setMaximum(MAX);
			long startTime = 0;

			String selectFailedFol = "select * from icdocfolders where Export_Status <>'SUCCESS'";
			LOGGER.debug("selectFailedFol:"+selectFailedFol);
			ResultSet selectFailedFolResultSet = selectAccessDataSTMT.executeQuery(selectFailedFol);
			String documentCode, numberSign, ObjectId, exportDate, exportStatus;
			extractExportFailedFolPBThread = new Thread(extractExportFailedFolPBRnnable);
			extractExportFailedFolPBThread.start();
			
			HashMap custFolderAttributeHashMap = new HashMap(); 
			String isCustFolderCreated = null;
			String codeV, subjectV, numberSignV, creatorNameV, branchV, verifierNameV, dateEnforceV =null ;
			String docAbbreviateNameV,typeDetailV,faCIFV,faIDV,faNameV,participateV,statusNameV =null;
			String originalV,specificDocNameV,tsdbNameV,depNameV,depNameTWV,nameGroupV,codeGroupV=null;
			String statusCodeV,docAbbreviateCodeV,participateCodeV,fieldActionCodeV,tsdbCodeV,SpecificDocCodeV,creditCouncilV=null;
			String folderQuery = null;
			ResultSet folderResultset = null;
			long endTime = 0, resultSetCount = 0;
			
			while (selectFailedFolResultSet.next()) {

				startTime = System.currentTimeMillis();
				documentCode = selectFailedFolResultSet.getString("Folder_Code");
				numberSign = selectFailedFolResultSet.getString("Number_Sign");
				ObjectId = selectFailedFolResultSet.getString("Object_Id");
				exportDate = selectFailedFolResultSet.getString("Export_Date");
				exportStatus = selectFailedFolResultSet.getString("Export_Status");
				folderQuery = RSB.getString("ICDOCFOLDERQUERY")+" where a.[Number_Sign] = '"+numberSign+"'";
				LOGGER.debug("folderQuery:"+folderQuery);
				folderResultset = sqlStatementFailedFol.executeQuery(folderQuery);	
				
				while (folderResultset.next()) {
					startTime = System.currentTimeMillis();
					branchV = folderResultset.getString("Branch");
					codeV = folderResultset.getString("Code");
					subjectV = folderResultset.getString("Subject");
					numberSignV = folderResultset.getString("Number_Sign");
					creatorNameV = 	folderResultset.getString("Creator");
					verifierNameV = folderResultset.getString("Verifier");
					dateEnforceV = folderResultset.getString("Date_Enforce");
					docAbbreviateNameV = folderResultset.getString("DocAbbreviate");
					typeDetailV = folderResultset.getString("TypeDetail");
					faCIFV = folderResultset.getString("FA_CIF");
					faIDV = folderResultset.getString("FA_ID");
					faNameV = 	folderResultset.getString("FA_Name");
					participateV = folderResultset.getString("Participate");
					statusNameV = folderResultset.getString("Status_Name");
					originalV = folderResultset.getString("Original");
					specificDocNameV = folderResultset.getString("SpecificDoc_Name");
					tsdbNameV = folderResultset.getString("TSDB_Name");
					depNameV = folderResultset.getString("Dep_name");
					depNameTWV = 	folderResultset.getString("Dep_name_TW");
					nameGroupV = folderResultset.getString("name_group");
					codeGroupV = folderResultset.getString("code_group");
					statusCodeV = folderResultset.getString("Status");
					docAbbreviateCodeV = folderResultset.getString("DocAbbreviate_Code");
					participateCodeV = folderResultset.getString("Participate_code");
					fieldActionCodeV = 	folderResultset.getString("FieldAction_Code");
					tsdbCodeV = folderResultset.getString("TSDB");
					SpecificDocCodeV = folderResultset.getString("SpecificDoc");
					creditCouncilV = folderResultset.getString("CreditCouncil");
			
					custFolderAttributeHashMap.put("branch_number",branchV);
					custFolderAttributeHashMap.put("code",codeV);
					custFolderAttributeHashMap.put("folder_subject",subjectV);
					custFolderAttributeHashMap.put("number_sign",numberSignV);
					custFolderAttributeHashMap.put("creator_name",creatorNameV);
					custFolderAttributeHashMap.put("verifier_name",verifierNameV);
					custFolderAttributeHashMap.put("date_enforce",dateEnforceV);
					custFolderAttributeHashMap.put("doc_abbreviate_name",docAbbreviateNameV);
					custFolderAttributeHashMap.put("type_detail",typeDetailV);
					custFolderAttributeHashMap.put("fa_cif",faCIFV);
					custFolderAttributeHashMap.put("fa_id",faIDV);
					custFolderAttributeHashMap.put("fa_name",faNameV);
					custFolderAttributeHashMap.put("participate",participateV);
					custFolderAttributeHashMap.put("status_name",statusNameV);
					custFolderAttributeHashMap.put("original",originalV);
					custFolderAttributeHashMap.put("specific_doc_name",specificDocNameV);
					custFolderAttributeHashMap.put("tsdb_name",tsdbNameV);
					custFolderAttributeHashMap.put("dep_name",depNameV);
					custFolderAttributeHashMap.put("dep_name_tw",depNameTWV);
					custFolderAttributeHashMap.put("name_group",nameGroupV);
					custFolderAttributeHashMap.put("code_group",codeGroupV);
					custFolderAttributeHashMap.put("status_code",statusCodeV);
					custFolderAttributeHashMap.put("doc_abbreviate_code",docAbbreviateCodeV);
					custFolderAttributeHashMap.put("participate_code",participateCodeV);
					custFolderAttributeHashMap.put("field_action_code",fieldActionCodeV);
					custFolderAttributeHashMap.put("tsdb_code",tsdbCodeV);
					custFolderAttributeHashMap.put("specific_doc_code",SpecificDocCodeV);
					custFolderAttributeHashMap.put("credit_council",creditCouncilV);				
					custFolderAttributeHashMap.put("branch_cabinet",branchCode);
					custFolderAttributeHashMap.put("source_folder_path",sourceFolderPath);
					isCustFolderCreated = doCreateCustFolder(custFolderAttributeHashMap, session, stmt3, accessstmt4, accConn, sqlConn);
					LOGGER.debug("isCustFolderCreated:"+isCustFolderCreated);
					accessDatabase2.updateExportedFolderIntoAccessDB(codeV, numberSignV, Calendar.getInstance().getTime().toString(), isCustFolderCreated, accessstmt4);
					accessConnectionG.commit();
					current++;
					resultSetCount = resultSetCount + 1;
					endTime = System.currentTimeMillis();
					WAIT = endTime - startTime;
				}

			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			LOGGER.error("ExportToDocumentum  :: doExportFailedCustDocs :: ED009" + e);
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			LOGGER.error("ExportToDocumentum  :: doExportFailedCustDocs :: ED010" + e);
			e.printStackTrace();
		} finally {
			LOGGER.debug("ExportToDocumentum  :: doExportFailedCustDocs :: Exit from Method");
		}
	}
	
	
	protected void executeCheckoutOperation(IDfSession m_session, String objectId) throws IOException {
		try {
			IDfId sysObjId = new DfId(objectId);
			IDfSysObject checkoutObject = (IDfSysObject) m_session.getObject(sysObjId);
			IDfCheckoutOperation checkoutOperation = new DfCheckoutOperation();
			if (checkoutObject.isCheckedOut()) {
				LOGGER.debug("\nWarning: The object/virtual document is already checked out and locked!");
				LOGGER.debug("Checkout Operation failed!");
				checkoutObject.cancelCheckout();
			} else {
				IDfCheckoutNode node = (IDfCheckoutNode) checkoutOperation.add(checkoutObject);
				if (checkoutOperation.execute() == false) {
					LOGGER.debug("\nCheckout Operation failed!");
				} else {
					LOGGER.debug("\nCheckout Operation successful!");
				}
			}
		}
		catch (DfException dfe) {
			LOGGER.debug("\nError: executeCheckoutOperation(): " + dfe.toString());
		}
	}
	
	/*
	 * Create Customer Folder if Not exist
	 */
	protected void isCustFolderExist(String destFolderPathFA, String numberSignFA) throws DfException {
		String folderNameFA = numberSignFA.replaceAll("/", "-");		
		String linkTo = destFolderPathFA.replaceAll("/"+folderNameFA, "");
		LOGGER.debug("ExportToDocumentum  :: isCustFolderExist :: folderNameFA"+folderNameFA+" linkTo"+linkTo);
		IDfFolder idfParentFolderObjFA = (IDfFolder) session.getObjectByPath(destFolderPathFA);
		if (idfParentFolderObjFA == null) {
			LOGGER.debug("ExportToDocumentum  :: isCustFolderExist :: folder not exist creation");
			IDfFolder icDocFolderObjFA = (IDfFolder) session.newObject(ICDOC_FOLDER_TYPE);
			icDocFolderObjFA.setString("number_sign", numberSignFA);
			icDocFolderObjFA.setSubject("Update Folder Properties");
			icDocFolderObjFA.link(linkTo);
			icDocFolderObjFA.setObjectName(folderNameFA);
			icDocFolderObjFA.save();
		} else {
			LOGGER.debug("ExportToDocumentum  :: isCustFolderExist :: folder exist");
		}
	}

	/**
	 * Used to create Session from Session Manager
	 * 
	 * @param docbase
	 * @param user
	 * @param password
	 * @return
	 * @throws DfException
	 */
	public static IDfSession createSession(String docbase, String username, String password) throws DfException {
		LOGGER.debug("ExportToDocumentum  :: createSession :: Enter into Method");
		sMgr = getInitializedSessionManager(docbase, username, password);
		session = sMgr.getSession(docbase);
		if (session != null) {
			LOGGER.debug("ExportToDocumentum  :: createSession :: Session Created Successfully.");
		}
		LOGGER.debug("ExportToDocumentum  :: createSession :: Exit from Method");
		return session;
	}

	/**
	 * Used to release Session
	 */
	public static void releaseSession() {
		sMgr.release(session);
		LOGGER.debug("ExportToDocumentum  :: releaseSession :: Session Released.");
	}

	/**
	 * Used to create Session Manager
	 * 
	 * @param docbase
	 * @param user
	 * @param password
	 * @return
	 * @throws DfException
	 */
	private static IDfSessionManager getInitializedSessionManager(String docbase, String username, String password) throws DfException {
		IDfSessionManager idfsessionmanager = DfClient.getLocalClient().newSessionManager();
		IDfLoginInfo idflogininfo = (new DfClientX()).getLoginInfo();
		idflogininfo.setUser(username);
		idflogininfo.setPassword(password);
		idfsessionmanager.setIdentity(docbase, idflogininfo);
		return idfsessionmanager;
	}

	class SimulatedActivity extends SwingWorker<Void, Integer> {
		/**
		 * Constructs the simulated activity that increments a counter from 0 to
		 * a given target.
		 * 
		 * @param t
		 *            the target value of the counter.
		 */
		public SimulatedActivity(int t) {
			current = 0;
			target = t;
		}

		protected Void doInBackground() throws Exception {
			try {
				while (current < target) {
					Thread.sleep(WAIT);
					// current++;
					publish(current);
				}
			} catch (InterruptedException e) {
				LOGGER.error("ExportToDocumentum  :: doInBackground :: ED011" + e);
				e.printStackTrace();
			}
			return null;
		}

		protected void process(List<Integer> chunks) {
			for (Integer chunk : chunks) {
				jpb.setValue(chunk);
			}
		}

		protected void done() {
			rerunButtonV.setEnabled(true);
		}

		private int target;
	}

	Runnable extractExportFailedDocsPBRnnable = new Runnable() {
		public void run() {
			try {
				activity = new SimulatedActivity(MAX);
				activity.execute();
			} catch (Exception iex) {
				LOGGER.error("ExportToDocumentum  :: extractExportFailedDocsPBRnnable :: ED012" + iex);
				iex.printStackTrace();
			}
		}
	};
	
	Runnable extractExportFailedFolPBRnnable = new Runnable() {
		public void run() {
			try {
				activity = new SimulatedActivity(MAX);
				activity.execute();
			} catch (Exception iex) {
				LOGGER.error("ExportToDocumentum  :: extractExportFailedFolPBRnnable :: ED012" + iex);
				iex.printStackTrace();
			}
		}
	};

}